<template>
  <div class="auto-assign">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单自动分配规则</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddRule">
          <el-icon><Plus /></el-icon>新建规则
        </el-button>
      </div>
    </div>

    <!-- 规则列表 -->
    <el-card class="rule-list">
      <el-table
        v-loading="loading"
        :data="ruleList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="strategy" label="分配策略" width="120">
          <template #default="{ row }">
            <el-tag :type="getStrategyTag(row.strategy)">
              {{ getStrategyLabel(row.strategy) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getPriorityTag(row.priority)">
              {{ getPriorityLabel(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handlerCount" label="处理人数" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleCopy(row)">复制</el-button>
            <el-button type="warning" link @click="handlePreview(row)">预览</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 规则编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建规则' : '编辑规则'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="异常类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择异常类型">
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="分配策略" prop="strategy">
          <el-select v-model="form.strategy" placeholder="请选择分配策略">
            <el-option label="轮询分配" value="round_robin" />
            <el-option label="负载均衡" value="load_balance" />
            <el-option label="固定分配" value="fixed" />
            <el-option label="智能分配" value="smart" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="form.priority" placeholder="请选择优先级">
            <el-option label="最高" value="highest" />
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
            <el-option label="最低" value="lowest" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理角色" prop="handlers">
          <el-select
            v-model="form.handlers"
            multiple
            collapse-tags
            placeholder="请选择处理角色"
          >
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配条件" prop="conditions">
          <div class="condition-list">
            <div
              v-for="(condition, index) in form.conditions"
              :key="index"
              class="condition-item"
            >
              <div class="condition-header">
                <span class="condition-title">条件 {{ index + 1 }}</span>
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveCondition(index)"
                >
                  删除
                </el-button>
              </div>
              <div class="condition-content">
                <el-form-item
                  :prop="'conditions.' + index + '.field'"
                  :rules="{ required: true, message: '请选择条件字段', trigger: 'change' }"
                >
                  <el-select v-model="condition.field" placeholder="条件字段">
                    <el-option label="订单金额" value="amount" />
                    <el-option label="客户等级" value="customer_level" />
                    <el-option label="服务类型" value="service_type" />
                    <el-option label="异常原因" value="reason" />
                    <el-option label="紧急程度" value="urgency" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'conditions.' + index + '.operator'"
                  :rules="{ required: true, message: '请选择运算符', trigger: 'change' }"
                >
                  <el-select v-model="condition.operator" placeholder="运算符">
                    <el-option label="等于" value="eq" />
                    <el-option label="不等于" value="ne" />
                    <el-option label="大于" value="gt" />
                    <el-option label="大于等于" value="ge" />
                    <el-option label="小于" value="lt" />
                    <el-option label="小于等于" value="le" />
                    <el-option label="包含" value="in" />
                    <el-option label="不包含" value="nin" />
                  </el-select>
                </el-form-item>
                <el-form-item
                  :prop="'conditions.' + index + '.value'"
                  :rules="{ required: true, message: '请输入条件值', trigger: 'blur' }"
                >
                  <el-input
                    v-if="condition.field === 'amount'"
                    v-model.number="condition.value"
                    type="number"
                    placeholder="金额"
                  >
                    <template #append>元</template>
                  </el-input>
                  <el-select
                    v-else-if="condition.field === 'customer_level'"
                    v-model="condition.value"
                    placeholder="客户等级"
                  >
                    <el-option label="普通会员" value="normal" />
                    <el-option label="银卡会员" value="silver" />
                    <el-option label="金卡会员" value="gold" />
                    <el-option label="钻石会员" value="diamond" />
                  </el-select>
                  <el-select
                    v-else-if="condition.field === 'service_type'"
                    v-model="condition.value"
                    placeholder="服务类型"
                  >
                    <el-option label="普通洗护" value="normal" />
                    <el-option label="特殊洗护" value="special" />
                    <el-option label="奢侈品洗护" value="luxury" />
                  </el-select>
                  <el-select
                    v-else-if="condition.field === 'urgency'"
                    v-model="condition.value"
                    placeholder="紧急程度"
                  >
                    <el-option label="普通" value="normal" />
                    <el-option label="紧急" value="urgent" />
                    <el-option label="特急" value="very_urgent" />
                  </el-select>
                  <el-input
                    v-else
                    v-model="condition.value"
                    placeholder="条件值"
                  />
                </el-form-item>
              </div>
            </div>
            <div class="condition-actions">
              <el-button type="primary" @click="handleAddCondition">
                <el-icon><Plus /></el-icon>添加条件
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="负载均衡" v-if="form.strategy === 'load_balance'">
          <el-form-item label="最大负载" prop="maxLoad">
            <el-input-number
              v-model="form.maxLoad"
              :min="1"
              :max="100"
              placeholder="最大负载数"
            />
          </el-form-item>
          <el-form-item label="负载权重" prop="loadWeights">
            <div class="weight-list">
              <div
                v-for="(weight, index) in form.loadWeights"
                :key="index"
                class="weight-item"
              >
                <el-select
                  v-model="weight.roleId"
                  placeholder="选择角色"
                  style="width: 200px"
                >
                  <el-option
                    v-for="role in roleList"
                    :key="role.id"
                    :label="role.name"
                    :value="role.id"
                  />
                </el-select>
                <el-input-number
                  v-model="weight.value"
                  :min="1"
                  :max="100"
                  placeholder="权重值"
                  style="width: 150px"
                />
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveWeight(index)"
                >
                  删除
                </el-button>
              </div>
              <div class="weight-actions">
                <el-button type="primary" @click="handleAddWeight">
                  <el-icon><Plus /></el-icon>添加权重
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="智能分配" v-if="form.strategy === 'smart'">
          <el-form-item label="分配模型" prop="model">
            <el-select v-model="form.model" placeholder="请选择分配模型">
              <el-option label="历史处理量" value="history" />
              <el-option label="处理效率" value="efficiency" />
              <el-option label="满意度评分" value="satisfaction" />
              <el-option label="综合评分" value="comprehensive" />
            </el-select>
          </el-form-item>
          <el-form-item label="模型权重" prop="modelWeights">
            <div class="weight-list">
              <div
                v-for="(weight, index) in form.modelWeights"
                :key="index"
                class="weight-item"
              >
                <el-select
                  v-model="weight.field"
                  placeholder="选择指标"
                  style="width: 200px"
                >
                  <el-option label="历史处理量" value="history" />
                  <el-option label="处理效率" value="efficiency" />
                  <el-option label="满意度评分" value="satisfaction" />
                </el-select>
                <el-input-number
                  v-model="weight.value"
                  :min="0"
                  :max="100"
                  placeholder="权重值"
                  style="width: 150px"
                />
                <el-button
                  type="danger"
                  link
                  @click="handleRemoveModelWeight(index)"
                >
                  删除
                </el-button>
              </div>
              <div class="weight-actions">
                <el-button type="primary" @click="handleAddModelWeight">
                  <el-icon><Plus /></el-icon>添加权重
                </el-button>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 规则预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="规则预览"
      width="800px"
    >
      <div class="rule-preview">
        <div class="preview-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="规则名称">
              {{ currentRule.name }}
            </el-descriptions-item>
            <el-descriptions-item label="异常类型">
              <el-tag :type="getExceptionTypeTag(currentRule.type)">
                {{ getExceptionTypeLabel(currentRule.type) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="分配策略">
              <el-tag :type="getStrategyTag(currentRule.strategy)">
                {{ getStrategyLabel(currentRule.strategy) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityTag(currentRule.priority)">
                {{ getPriorityLabel(currentRule.priority) }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="preview-section">
          <h3>处理角色</h3>
          <div class="handler-list">
            <el-tag
              v-for="handler in currentRule.handlers"
              :key="handler"
              class="mx-1"
            >
              {{ getRoleName(handler) }}
            </el-tag>
          </div>
        </div>
        <div class="preview-section">
          <h3>分配条件</h3>
          <el-table :data="currentRule.conditions" border>
            <el-table-column prop="field" label="条件字段" width="150">
              <template #default="{ row }">
                {{ getConditionFieldLabel(row.field) }}
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="运算符" width="120">
              <template #default="{ row }">
                {{ getOperatorLabel(row.operator) }}
              </template>
            </el-table-column>
            <el-table-column prop="value" label="条件值" />
          </el-table>
        </div>
        <div class="preview-section" v-if="currentRule.strategy === 'load_balance'">
          <h3>负载均衡配置</h3>
          <el-table :data="currentRule.loadWeights" border>
            <el-table-column prop="roleId" label="处理角色" width="200">
              <template #default="{ row }">
                {{ getRoleName(row.roleId) }}
              </template>
            </el-table-column>
            <el-table-column prop="value" label="权重值" width="120" />
          </el-table>
        </div>
        <div class="preview-section" v-if="currentRule.strategy === 'smart'">
          <h3>智能分配配置</h3>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="分配模型">
              {{ getModelLabel(currentRule.model) }}
            </el-descriptions-item>
          </el-descriptions>
          <el-table :data="currentRule.modelWeights" border>
            <el-table-column prop="field" label="指标" width="200">
              <template #default="{ row }">
                {{ getModelFieldLabel(row.field) }}
              </template>
            </el-table-column>
            <el-table-column prop="value" label="权重值" width="120" />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantOrderExceptionAssignRuleList,
  addMerchantOrderExceptionAssignRule,
  updateMerchantOrderExceptionAssignRule,
  deleteMerchantOrderExceptionAssignRule,
  copyMerchantOrderExceptionAssignRule,
  updateMerchantOrderExceptionAssignRuleStatus,
  getMerchantRoleList
} from '@/api/merchant'

// 规则列表数据
const loading = ref(false)
const ruleList = ref([])
const roleList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: '',
  strategy: '',
  priority: '',
  handlers: [],
  conditions: [],
  maxLoad: 10,
  loadWeights: [],
  model: '',
  modelWeights: [],
  remark: ''
})

// 预览相关
const previewVisible = ref(false)
const currentRule = ref({})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择异常类型', trigger: 'change' }
  ],
  strategy: [
    { required: true, message: '请选择分配策略', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  handlers: [
    { required: true, message: '请选择处理角色', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一个处理角色', trigger: 'change' }
  ],
  conditions: [
    { required: true, message: '请添加分配条件', trigger: 'change' },
    { type: 'array', min: 1, message: '至少添加一个条件', trigger: 'change' }
  ]
}

// 获取规则列表
const getRuleList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionAssignRuleList()
    ruleList.value = data
  } catch (error) {
    console.error('获取规则列表失败:', error)
    ElMessage.error('获取规则列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const { data } = await getMerchantRoleList()
    roleList.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 新建规则
const handleAddRule = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = Array.isArray(form[key]) ? [] : ''
  })
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 复制规则
const handleCopy = async (row) => {
  try {
    await copyMerchantOrderExceptionAssignRule(row.id)
    ElMessage.success('复制成功')
    getRuleList()
  } catch (error) {
    console.error('复制规则失败:', error)
  }
}

// 预览规则
const handlePreview = (row) => {
  currentRule.value = row
  previewVisible.value = true
}

// 删除规则
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该规则吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantOrderExceptionAssignRule(row.id)
    ElMessage.success('删除成功')
    getRuleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规则失败:', error)
    }
  }
}

// 更新状态
const handleStatusChange = async (row) => {
  try {
    await updateMerchantOrderExceptionAssignRuleStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加条件
const handleAddCondition = () => {
  form.conditions.push({
    field: '',
    operator: '',
    value: ''
  })
}

// 删除条件
const handleRemoveCondition = (index) => {
  form.conditions.splice(index, 1)
}

// 添加负载权重
const handleAddWeight = () => {
  form.loadWeights.push({
    roleId: '',
    value: 50
  })
}

// 删除负载权重
const handleRemoveWeight = (index) => {
  form.loadWeights.splice(index, 1)
}

// 添加模型权重
const handleAddModelWeight = () => {
  form.modelWeights.push({
    field: '',
    value: 33
  })
}

// 删除模型权重
const handleRemoveModelWeight = (index) => {
  form.modelWeights.splice(index, 1)
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantOrderExceptionAssignRule(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantOrderExceptionAssignRule(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getRuleList()
  } catch (error) {
    console.error('保存规则失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取分配策略标签类型
const getStrategyTag = (strategy) => {
  const strategyMap = {
    round_robin: 'primary',
    load_balance: 'success',
    fixed: 'warning',
    smart: 'info'
  }
  return strategyMap[strategy] || ''
}

// 获取分配策略标签文本
const getStrategyLabel = (strategy) => {
  const strategyMap = {
    round_robin: '轮询分配',
    load_balance: '负载均衡',
    fixed: '固定分配',
    smart: '智能分配'
  }
  return strategyMap[strategy] || strategy
}

// 获取优先级标签类型
const getPriorityTag = (priority) => {
  const priorityMap = {
    highest: 'danger',
    high: 'warning',
    medium: 'primary',
    low: 'info',
    lowest: ''
  }
  return priorityMap[priority] || ''
}

// 获取优先级标签文本
const getPriorityLabel = (priority) => {
  const priorityMap = {
    highest: '最高',
    high: '高',
    medium: '中',
    low: '低',
    lowest: '最低'
  }
  return priorityMap[priority] || priority
}

// 获取条件字段标签文本
const getConditionFieldLabel = (field) => {
  const fieldMap = {
    amount: '订单金额',
    customer_level: '客户等级',
    service_type: '服务类型',
    reason: '异常原因',
    urgency: '紧急程度'
  }
  return fieldMap[field] || field
}

// 获取运算符标签文本
const getOperatorLabel = (operator) => {
  const operatorMap = {
    eq: '等于',
    ne: '不等于',
    gt: '大于',
    ge: '大于等于',
    lt: '小于',
    le: '小于等于',
    in: '包含',
    nin: '不包含'
  }
  return operatorMap[operator] || operator
}

// 获取分配模型标签文本
const getModelLabel = (model) => {
  const modelMap = {
    history: '历史处理量',
    efficiency: '处理效率',
    satisfaction: '满意度评分',
    comprehensive: '综合评分'
  }
  return modelMap[model] || model
}

// 获取模型指标标签文本
const getModelFieldLabel = (field) => {
  const fieldMap = {
    history: '历史处理量',
    efficiency: '处理效率',
    satisfaction: '满意度评分'
  }
  return fieldMap[field] || field
}

// 获取角色名称
const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role ? role.name : roleId
}

onMounted(() => {
  getRuleList()
  getRoleList()
})
</script>

<style lang="scss" scoped>
.auto-assign {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .rule-list {
    margin-bottom: 20px;
  }

  .condition-list {
    .condition-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      .condition-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .condition-title {
          font-weight: 500;
        }
      }

      .condition-content {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 15px;
      }
    }

    .condition-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .weight-list {
    .weight-item {
      display: flex;
      align-items: center;
      gap: 10px;
      margin-bottom: 10px;
    }

    .weight-actions {
      margin-top: 10px;
      text-align: center;
    }
  }

  .rule-preview {
    .preview-section {
      margin-bottom: 20px;

      h3 {
        margin: 0 0 15px;
        font-size: 16px;
        font-weight: 500;
      }

      .handler-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;

        .mx-1 {
          margin: 0 4px;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 